package game;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.JOptionPane;

/**
 * A class that will provide the option to save if a player has progressed to the
 * take turns stage of the game
 * 
 * @author Dhruv Nayar
 */

public class GameCloseListener implements WindowListener {

    private GameDriver driver;

    GameCloseListener(GameDriver driver) {
	this.driver = driver;
    }

    @Override
    public void windowOpened(WindowEvent e) {
	// TODO Auto-generated method stub
    }

    @Override
    public void windowClosing(WindowEvent e) {

	if (driver.currentGame.getPhase() == 0
		|| driver.currentGame.getPhase() == 3)
	    System.exit(0);

	driver.round.stopTimer();
	int reply = JOptionPane.showConfirmDialog(null,
		"Do you want to save before closing?", "Save Game?",
		JOptionPane.YES_NO_OPTION);

	if (reply == JOptionPane.YES_OPTION) {

	    try {
		FileOutputStream fileOut = new FileOutputStream("mule.ser");
		ObjectOutputStream out = new ObjectOutputStream(fileOut);
		out.writeObject(new SaveGame(driver.currentGame, driver.round
			.getRound(), driver.round.getPlayerInt(),
			driver.round.getMapPanel(), driver.round
				.getSecondsLeft()));
		out.close();
		fileOut.close();
	    } catch (IOException i) {
		i.printStackTrace();
	    }

	    JOptionPane.showMessageDialog(null, "Game Saved, Goodbye");
	    System.exit(0);
	}
	if (reply == JOptionPane.NO_OPTION) {
//	    JOptionPane.showMessageDialog(null, "Goodbye");
	    System.exit(0);
	}

	else {
	    driver.round.startTimer();
	}
    }

    @Override
    public void windowClosed(WindowEvent e) {
	// TODO Auto-generated method stub
    }

    @Override
    public void windowIconified(WindowEvent e) {
	// TODO Auto-generated method stub
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
	// TODO Auto-generated method stub
    }

    @Override
    public void windowActivated(WindowEvent e) {
	// TODO Auto-generated method stub
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
	// TODO Auto-generated method stub
    }
}